package com.example.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.Order;
import com.example.service.OrderService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 分库分表 Order
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private OrderService orderService;

    @GetMapping("/list")
    public List<Order> listAll() {
        return orderService.list();
    }

    @GetMapping("/add")
    public String add() {
        Random random = new Random();
        int randomInt = random.nextInt(1000);

        Order order = new Order();
        order.setUserId(99 + randomInt);
        order.setName("hello" + randomInt);
        order.setMoney((long) randomInt);
        order.setOrderDate(new Date());
        order.setProductId(10 + randomInt);
        orderService.save(order);
        return "success";
    }

    @GetMapping("/add_100")
    public String add100() {
        for (int i = 0; i < 100; i++) {
            add();
        }
        return "success";
    }

    @GetMapping("/page/{limit}/{size}")
    public Page<Order> page(@PathVariable Long limit, @PathVariable Long size) {
        Page<Order> orderPage = new Page<>(limit, size);
        // 增加排序字段
        orderPage.addOrder(OrderItem.asc("user_id"));
        // 去除排序
        orderPage.setOrders(new ArrayList<>());
        return orderService.page(orderPage);
    }

}
